package com.it.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.mapper.UserMapper;
import com.it.entity.User;
import com.it.service.UserService;

/**
 * 实现类
 *
 * @author hua
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 存储数据库的同时，存储到缓存
     */
    @Override
    @CachePut(value = "user", key = "#result.id", unless = "#result eq null")
    public User insert(User user) {
        this.save(user);
        return user;
    }

    /**
     * 优先从redis缓存中读取（发现控制台并未执行sql）。如果缓存过期，则重新查数据，重新写入缓存
     */
    @Override
    @Cacheable(value = "user", key = "#userId", unless = "#result eq null")
    public User findUser(Integer userId) {
        User user = this.getById(userId);
        return user;
    }

    /**
     * 优先从redis缓存中读取（发现控制台并未执行sql）。如果缓存过期，则重新查数据，重新写入缓存
     * 自定义key,注意这里是keyGenerator= 而不是key=
     */
    @Override
    @Cacheable(value = "user", keyGenerator = "selfKeyGenerate")
    public User findUserSelfKey(Integer userId) {
        User user = this.getById(userId);
        return user;
    }

    /**
     * 删除数据时同样清除缓存
     */
    @Override
    @CacheEvict(value = "user", key = "#userId")
    public void delete(Integer userId) {
        this.removeById(userId);
    }

}
